"use client";

import { Card, List, Button, App } from "antd";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
import { useRouter } from "next/navigation";
import { api } from "~/trpc/react";
import { StepActions } from "./StepActions";
import { DeleteOutlined, EditOutlined } from "@ant-design/icons";
import type { Step } from "@prisma/client";
import { useState } from "react";
import { StepForm } from "./StepForm";
import type { DropResult, DroppableProps } from "react-beautiful-dnd";

interface StepListProps {
  courseId: string;
  taskId: string;
}

export function StepList({ courseId, taskId }: StepListProps) {
  const [editingStep, setEditingStep] = useState<Step | null>(null);
  const router = useRouter();
  const { message, modal } = App.useApp();

  const { data: task, isLoading, refetch } = api.tasks.getWithSteps.useQuery({
    taskId,
  });

  const deleteMutation = api.steps.delete.useMutation({
    onSuccess: () => {
      message.success("步骤删除成功");
      refetch();
    },
  });

  const reorderMutation = api.steps.reorder.useMutation({
    onSuccess: () => {
      message.success("步骤顺序已更新");
      refetch();
    },
    onError: (error) => {
      message.error("更新步骤顺序失败");
      console.error("重新排序步骤时出错:", error);
    },
  });

  const handleEdit = (step: Step) => {
    setEditingStep(step);
  };

  const handleDelete = async (step: Step) => {
    try {
      const confirmed = await modal.confirm({
        title: "确认删除",
        content: "确定要删除这个步骤吗？此操作不可恢复。",
        okText: "确认",
        cancelText: "取消",
        okButtonProps: {
          danger: true,
        },
      });

      if (confirmed) {
        await deleteMutation.mutateAsync(step.id);
      }
    } catch (error) {
      console.error("删除步骤时出错:", error);
    }
  };

  const handleDragEnd = async (result: DropResult) => {
    if (!result.destination || !task?.steps) return;

    const items = Array.from(task.steps);
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);

    // 更新所有受影响的步骤的 orderIndex
    const updates = items.map((step, index) => ({
      id: step.id,
      orderIndex: index,
    }));

    try {
      await reorderMutation.mutateAsync({
        taskId,
        updates,
      });
    } catch (error) {
      console.error("重新排序步骤时出错:", error);
    }
  };

  // 如果正在加载或没有步骤，显示适当的UI
  if (isLoading) {
    return <div>加载中...</div>;
  }

  if (!task?.steps?.length) {
    return (
      <div className="space-y-4">
        <div className="flex justify-between items-center">
          <h2 className="text-2xl font-bold">步骤管理</h2>
          <StepActions taskId={taskId} onSuccess={refetch} />
        </div>
        <div className="text-center py-8 text-gray-500">
          还没有步骤，点击右上角添加新步骤
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4 max-w-4xl mx-auto">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold">步骤管理</h2>
        <StepActions taskId={taskId} onSuccess={refetch} />
      </div>

      <DragDropContext onDragEnd={handleDragEnd}>
        <Droppable 
          droppableId="steps" 
          isDropDisabled={false}
          isCombineEnabled={false}
          mode="vertical"
          type="STEP"
        >
          {(provided, snapshot) => (
            <div 
              {...provided.droppableProps} 
              ref={provided.innerRef}
              className={`
                w-full transition-all duration-200 rounded-lg
                ${snapshot.isDraggingOver ? 'bg-gray-50/80 p-2' : ''}
              `}
            >
              {task.steps.map((step, index) => (
                <Draggable 
                  key={step.id} 
                  draggableId={step.id} 
                  index={index}
                  isDragDisabled={false}
                >
                  {(provided, snapshot) => {
                    // 计算拖拽样式
                    const dragStyle = snapshot.isDragging
                      ? {
                          ...provided.draggableProps.style,
                          left: provided.draggableProps.style?.left,
                          top: provided.draggableProps.style?.top,
                        }
                      : {
                          transform: 'none',
                          transition: 'transform 0.2s ease-in-out',
                        };

                    return (
                      <div
                        ref={provided.innerRef}
                        {...provided.draggableProps}
                        className={`
                          mb-4 transition-all duration-200
                          ${snapshot.isDragging ? 'z-50' : 'z-0'}
                        `}
                        style={dragStyle}
                      >
                        <Card
                          className={`
                            w-full bg-white transition-all duration-200
                            ${snapshot.isDragging 
                              ? 'shadow-xl border-blue-400 border-2 scale-[1.02]' 
                              : 'hover:shadow-md hover:border-gray-300'
                            }
                            ${snapshot.draggingOver ? '-translate-y-1' : ''}
                          `}
                          bodyStyle={{ 
                            padding: '12px 16px',
                          }}
                        >
                          <div 
                            {...provided.dragHandleProps}
                            className={`
                              cursor-move select-none
                              ${snapshot.isDragging ? 'cursor-grabbing' : 'cursor-grab'}
                            `}
                          >
                            <div className="flex justify-between items-center group">
                              <div className="flex items-center gap-3">
                                <div className={`
                                  flex items-center justify-center w-6 h-6 
                                  rounded-full transition-colors duration-200
                                  ${snapshot.isDragging 
                                    ? 'bg-blue-100 text-blue-600' 
                                    : 'bg-gray-100 text-gray-500'
                                  }
                                `}>
                                  <span className="text-sm font-medium">
                                    {index + 1}
                                  </span>
                                </div>
                                <span className={`
                                  font-medium transition-colors duration-200
                                  ${snapshot.isDragging ? 'text-blue-600' : ''}
                                `}>
                                  {step.title}
                                </span>
                              </div>
                              <div className={`
                                space-x-1 transition-opacity duration-200
                                ${snapshot.isDragging ? 'opacity-0' : 'opacity-0 group-hover:opacity-100'}
                              `}>
                                <Button
                                  type="text"
                                  size="small"
                                  icon={<EditOutlined />}
                                  onClick={() => handleEdit(step)}
                                />
                                <Button
                                  type="text"
                                  size="small"
                                  danger
                                  icon={<DeleteOutlined />}
                                  onClick={() => handleDelete(step)}
                                />
                              </div>
                            </div>
                            {step.description && (
                              <p className="text-gray-600 mt-3 ml-9 line-clamp-2">
                                {step.description}
                              </p>
                            )}
                          </div>
                        </Card>
                      </div>
                    );
                  }}
                </Draggable>
              ))}
              {provided.placeholder}
            </div>
          )}
        </Droppable>
      </DragDropContext>

      <StepForm
        taskId={taskId}
        open={!!editingStep}
        initialValues={editingStep || undefined}
        onCancel={() => setEditingStep(null)}
        onSuccess={() => {
          setEditingStep(null);
          refetch();
        }}
      />
    </div>
  );
} 